package news.tencent.charco.android.view.fragment;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import cn.jzvd.JZMediaManager;
import cn.jzvd.JZUtils;
import cn.jzvd.JZVideoPlayer;
import cn.jzvd.JZVideoPlayerManager;
import news.tencent.charco.android.R;
import news.tencent.charco.android.base.BaseFragment;
import news.tencent.charco.android.entity.NewsEs;
import news.tencent.charco.android.mimc.MimcServer;
import news.tencent.charco.android.mimc.Msg;
import news.tencent.charco.android.mimc.MsgData;
import news.tencent.charco.android.mimc.MsgHandleInterface;
import news.tencent.charco.android.mimc.NewsEsSource;
import news.tencent.charco.android.utils.AnimationUtil;
import news.tencent.charco.android.utils.DbOperateUtil;
import news.tencent.charco.android.utils.ToastUtil;
import news.tencent.charco.android.view.activity.WebViewActivity;
import news.tencent.charco.android.view.adapter.NewsListAdapter;
import news.tencent.charco.android.widget.popup.LoseInterestPopup;

import static news.tencent.charco.android.view.fragment.NewsFragment.SEARCH_DETAIL;

/**
 * Created 18/7/19 16:39
 * Author:charcolee
 * Version:V1.0
 * ----------------------------------------------------
 * 文件描述：
 * ----------------------------------------------------
 */

public class NewsListFragment extends BaseFragment implements MsgHandleInterface, RecyclerView.OnChildAttachStateChangeListener, OnRefreshListener, BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener, LoseInterestPopup.OnLoseInterestListener {

    /**
     * 7*24小时快讯
     */
    public static final int NEWS_KUAIXUN = 0;
    /**
     * 要闻
     */
    public static final int NEWS_YW = 1;
    /**
     * 直播
     */
    public static final int NEWS_ZHIBO = 2;
    /**
     * 上市公司
     */
    public static final int NEWS_SSGS = 3;

    /**
     * 第一黄金网快讯
     */
    public static final int DYHJW_KX = 4;

    /**
     * 新闻详情
     */
    public static final int DETAIL = 10;
    /**
     * 关键字搜索
     */
    public static final int KEYWORD_SEARCH = 20;

    /**
     * 查询服务员
     */
    public static final String ADMIN_QUERY = "AdminQuery0829";
    /**
     * 详情服务员
     */
    public static final String ADMIN_DETAIL = "AdminDetail0829";

    private RecyclerView mRecyclerView;
    private SmartRefreshLayout mSmartRefreshLayout;
    private TextView mTvTip;
    private NewsListAdapter mAdapter;
    private long latestTime = 0;

    private int newsType = 0;

    private String src;

    private List<NewsEs> newsEsList = new ArrayList<>();

    MyHandler newsHandler = new MyHandler(this);

    private static ReentrantLock lockView = new ReentrantLock();

    static class MyHandler extends Handler {
        WeakReference<NewsListFragment> fragmentRef;

        MyHandler(NewsListFragment activity) {
            fragmentRef = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {

            NewsListFragment theActivity = fragmentRef.get();
            if (msg.what == 1) {
                theActivity.updateData();
                return;
            }

            MsgData msgData = (MsgData) msg.obj;
            if (null == msgData || msgData.getContent() == null || "".equals(msgData.getContent())) {
                ToastUtil.showToast("无详情");
                return;
            }
            Intent itemIntent = new Intent(theActivity.getActivity(), WebViewActivity.class);
            itemIntent.putExtra(WebViewActivity.key, msgData);
            theActivity.startActivity(itemIntent);
        }
    }


    public int getNews_type() {
        return newsType;
    }

    public void setNews_type(int news_type) {
        this.newsType = news_type;
    }

    public String getSrc() {
        return src;
    }

    public void setSrc(String src) {
        this.src = src;
    }

    //增加newInstance函数替代Fragment 的构造函数
    public static NewsListFragment newInstance(String src, int newsType) {
        NewsListFragment f = new NewsListFragment();
        f.setNews_type(newsType);
        f.setSrc(src);
        // 初始化消息服务
        MimcServer mimcServer = MimcServer.getInstance();
        mimcServer.addMsgHandle(f);
        return f;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_recommend_list;
    }

    @Override
    public void initView(View rootView) {
        mSmartRefreshLayout = findViewById(R.id.refreshLayout);
        mSmartRefreshLayout.setOnRefreshListener(this);
        mSmartRefreshLayout.setEnableOverScrollBounce(false);//是否启用越界回弹
        mSmartRefreshLayout.setEnableOverScrollDrag(false);
        mTvTip = findViewById(R.id.tv_tip);
        mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false));

        initList(newsEsList);
        mAdapter = new NewsListAdapter(newsEsList);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addOnChildAttachStateChangeListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    private void initList(List<NewsEs> newsEsList) {
        DbOperateUtil dbOperateUtil = DbOperateUtil.getInstance();
        List<NewsEsSource> list = dbOperateUtil.getAllByType(getStrNewsType(getNews_type()));
        for (NewsEsSource source : list) {
            NewsEs newsEs = new NewsEs();
            newsEs.setNewsEsSource(source);
            newsEsList.add(newsEs);
        }

        Collections.sort(newsEsList, new Comparator<NewsEs>() {
            @Override
            public int compare(NewsEs u1, NewsEs u2) {
                long diff = u1.getNewsEsSource().getIndexTime() - u2.getNewsEsSource().getIndexTime();
                if (diff > 0) {
                    return -1;
                } else if (diff < 0) {
                    return 1;
                }
                return 0; //相等为0
            }
        });

        if (newsEsList.size() > 0) {
            latestTime = newsEsList.get(0).getNewsEsSource().getIndexTime();
        }

        if (latestTime == 0){
            Msg msg = new Msg();
            msg.setLatestTime(0);
            msg.setSrc(getSrc());
            msg.setNewsType(getStrNewsType(getNews_type()));

            try {
                MimcServer mimcServer = MimcServer.getInstance();
                mimcServer.sendMessage(ADMIN_QUERY, msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void initListener() {
    }

    @Override
    protected void loadData() {
        return;
    }

    @Override
    public void onChildViewAttachedToWindow(View view) {

    }

    @Override
    public void onChildViewDetachedFromWindow(View view) {
        JZVideoPlayer jzvd = view.findViewById(R.id.video_player);
        if (jzvd != null) {
            Object[] dataSourceObjects = jzvd.dataSourceObjects;
            if (dataSourceObjects != null &&
                    JZUtils.dataSourceObjectsContainsUri(dataSourceObjects, JZMediaManager.getCurrentDataSource())) {
                JZVideoPlayer currentJzvd = JZVideoPlayerManager.getCurrentJzvd();
                if (currentJzvd != null && currentJzvd.currentScreen != JZVideoPlayer.SCREEN_WINDOW_FULLSCREEN) {
                    JZVideoPlayer.releaseAllVideos();
                }
            }
        }
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        askForNews();
        mSmartRefreshLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();
                mSmartRefreshLayout.finishRefresh(0);
            }
        }, 5000);

    }

    public void updateData() {
        mAdapter.notifyDataSetChanged();
        mSmartRefreshLayout.finishRefresh(0);
        AnimationUtil.showTipView(mTvTip, mRecyclerView);
    }

    private void askForNews() {
        Msg msg = new Msg();
        msg.setLatestTime(latestTime);
        msg.setSrc(getSrc());
        msg.setNewsType(getStrNewsType(getNews_type()));

        try {
            MimcServer mimcServer = MimcServer.getInstance();
            mimcServer.sendMessage(ADMIN_QUERY, msg);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getStrNewsType(int type) {
        switch (type) {
            case NEWS_KUAIXUN:
                return "news_kuaixun";
            case NEWS_YW:
                return "news_yw";
            case NEWS_ZHIBO:
                return "news_zhibo";
            case NEWS_SSGS:
                return "news_ssgs";
            case DYHJW_KX:
                return "dyhjw_kuaixun";
            case DETAIL:
                return "detail";
            default:
                return "news_kuaixun";
        }
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        NewsEs newsEs = mAdapter.getItem(position);
        if (null != newsEs) {
            Msg msg = new Msg();
            msg.setLatestTime(latestTime);
            msg.setSrc(getSrc());
            msg.setNewsType(getStrNewsType(getNews_type()));
            msg.setSubType(DETAIL);

            msg.setNewsId(newsEs.getNewsEsSource().getNid());

            try {
                MimcServer mimcServer = MimcServer.getInstance();
                mimcServer.sendMessage(ADMIN_DETAIL, msg);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        switch (view.getId()) {
            case R.id.iv_delete:
                new LoseInterestPopup(getActivity())
                        .setSource("腾讯新闻")
                        .setPosition(position)
                        .setOnLoseInterestListener(this)
                        .showPopup(view);
                break;
        }
    }


    @Override
    public void onLoseInterestListener(int poor_quality, int repeat, String source, int position) {
        ToastUtil.showToast("position = " + position);
    }

    @Override
    public void handleMsg(MsgData msgData) {
        if (null == msgData) {
            return;
        }

        if (null != msgData.getSubType() && msgData.getSubType() == KEYWORD_SEARCH) {
            return;
        }

        if (msgData.getSubType() == SEARCH_DETAIL) {
            return;
        }

        if (msgData.getTotal().equals(0)) {
            mSmartRefreshLayout.finishRefresh(0);
            ToastUtil.showToast("没有更多新闻");
            return;
        }

        String newsType = getStrNewsType(getNews_type());
        if (msgData.getNews_type().equals(newsType)) {
            if (null != msgData.getSubType() && msgData.getSubType() == DETAIL) {
                Message message = new Message();
                message.what = 0;
                message.obj = msgData;
                newsHandler.sendMessage(message);
                return;
            }

            NewsEs newsEs = new NewsEs();
            newsEs.setNewsEsSource(msgData);
            if (newsEsList.contains(newsEs)) {
                return;
            }

            newsEsList.add(newsEs);

            // 获取锁
            if (!lockView.tryLock()) {
                System.out.println("锁");
                return;
            }
            try {
                DbOperateUtil dbOperateUtil = DbOperateUtil.getInstance();
                dbOperateUtil.insert(newsEs.getNewsEsSource());
            } finally {
                lockView.unlock();
            }


            Collections.sort(newsEsList, new Comparator<NewsEs>() {
                @Override
                public int compare(NewsEs u1, NewsEs u2) {
                    long diff = u1.getNewsEsSource().getIndexTime() - u2.getNewsEsSource().getIndexTime();
                    if (diff > 0) {
                        return -1;
                    } else if (diff < 0) {
                        return 1;
                    }
                    return 0; //相等为0
                }
            });

            if (newsEsList.size() > 0) {
                latestTime = newsEsList.get(0).getNewsEsSource().getIndexTime();
            }

            if (newsEsList.size() > 200) {
                newsEsList.remove(newsEsList.size() - 1);
            }

            if (msgData.getTotal().equals(msgData.getCurIndex())) {
                Message message = new Message();
                message.what = 1;
                newsHandler.sendMessage(message);
            }
        }
    }

    @Override
    public void handleUnlimitGroupMsg(MsgData msgData) {
        if (null == msgData) {
            return;
        }

        if (!msgData.getNews_type().equals(getStrNewsType(getNews_type()))) {
            return;
        }
    }
}
